package mark.tom.hawk;

import android.content.Context;
import android.util.Base64;

import com.facebook.android.crypto.keychain.AndroidConceal;
import com.facebook.android.crypto.keychain.SharedPrefsBackedKeyChain;
import com.facebook.crypto.Crypto;
import com.facebook.crypto.CryptoConfig;
import com.facebook.crypto.Entity;
import com.facebook.crypto.keychain.KeyChain;
import com.facebook.soloader.SoLoader;

import androidx.annotation.NonNull;
import mark.tom.hawk.template.Encryption;

/**
 * @Description: Conceal加密接口实现
 * @Author: Tom.Shen
 * @Package: mark.tom.hawk
 * @Date: 2020/9/18
 * @Copyright: 版权归 Tom.Shen 所有
 */
public final class ConcealEncryption implements Encryption {

    private Crypto crypto;

    public ConcealEncryption(Context context) {
        try {
            SoLoader.init(context, false);
            KeyChain keyChain = new SharedPrefsBackedKeyChain(context, CryptoConfig.KEY_256);
            crypto = AndroidConceal.get().createDefaultCrypto(keyChain);
        } catch (Exception ex) {
            // ignore
        }
    }

    @Override
    public boolean hasInit() {
        return null!= crypto && crypto.isAvailable();
    }

    @Override
    public String encrypt(@NonNull String key, @NonNull String plainText) throws Exception {
        Entity entity = Entity.create(key);
        byte[] bytes = crypto.encrypt(plainText.getBytes(), entity);
        return Base64.encodeToString(bytes, Base64.NO_WRAP);
    }

    @Override
    public String decrypt(@NonNull String key, @NonNull String cipherText) throws Exception {
        Entity entity = Entity.create(key);
        byte[] decodedBytes = Base64.decode(cipherText, Base64.NO_WRAP);
        byte[] bytes = crypto.decrypt(decodedBytes, entity);
        return new String(bytes);
    }

}
